<template>
  <div class="categories">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="showDialog">添加分类</el-button>
      <table-tree
        :data="tableData"
        :selection-type="false"
        show-index
        index-text="#"
        :columns="columns"
        :expand-type="false"
        border
        :show-row-hover="false"
        style="margin-top: 30px"
      >
        <!-- 是否有效 -->
        <template slot="isValid" slot-scope="scope">
          <i
            class="el-icon-success icon-success"
            v-if="scope.row.cat_deleted == false"
          ></i>
          <i class="el-icon-error icon-error" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag type="danger" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="control" slot-scope="scope">
          <el-button
            type="success"
            @click="editData(scope.row)"
            style="margin-right: 15px"
            >编辑</el-button
          >
          <el-popconfirm title="是否删除此项？" @confirm="confirm(scope.row)">
            <el-button type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </table-tree>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[5, 10]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totle"
        :pager-count="5"
      >
      </el-pagination>

      <!-- 添加分类 -->
      <el-dialog
        title="添加商品分类"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input
              v-model="ruleForm.cat_name"
              style="width: 200px"
              autofocus="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="父级分类：">
            <el-cascader
              v-model="selectValue"
              value="cat_name"
              label="cat_name"
              :options="options"
              @change="handleChange"
              expandTrigger="hover"
              :props="cascaderProps"
              :clearable="true"
            ></el-cascader>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCategory">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑分类 -->
      <el-dialog
        title="修改分类"
        :visible.sync="editDialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form
          :model="editRuleForm"
          :rules="editRules"
          label-width="100px"
          ref="ruleForm1"
        >
          <el-form-item label="修改分类" prop="cat_name">
            <el-input v-model="editRuleForm.cat_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCategory">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import TableTree from ''
export default {
  components: {
    // TableTree,
  },
  data() {
    return {
      tableData: [], //页面总数据
      totle: 2, //总数据多少条
      //   pageSize: 10, //每页显示多少条
      //   currentPage: 1, //当前页
      query: {
        pagesize: 5, //每页显示多少条
        pagenum: 1, //当前页
      },
      columns: [
        //table配置
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isValid',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'control',
        },
      ],
      dialogVisible: false, //弹出
      ruleForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      rules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      options: [],
      selectValue: [], //级联选择器选中的值
      cascaderProps: {
        //选择器配置
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },

      editDialogVisible: false, //编辑

      editRuleForm: {
        cat_name: '',
        cat_id: null,
      },
      editRules: {
        cat_name: [
          { required: true, message: '请输入2-14字符', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const { data, meta } = await this.$axios.get(`/api/categories`, {
        params: this.query,
      })
      if (meta.status == 200) {
        this.tableData = data.result
        this.totle = data.total
      }
      //   console.log(data, meta)
    },
    showDialog() {
      this.dialogVisible = true
      this.getDialogFormData()
    },
    async getDialogFormData() {
      const { meta, data } = await this.$axios.get('/api/categories', {
        params: { type: 2 },
      })
      if (meta.status == 200) {
        this.options = data
      }
      //   console.log(data, meta)
    },

    handleChange() {
      //级联选择器选择值触发
      if (this.selectValue.length < 1) {
        this.ruleForm.cat_pid = this.ruleForm.cat_level =
          this.selectValue.length
      } else {
        this.ruleForm.cat_pid = this.selectValue.slice(-1)
        this.ruleForm.cat_level = this.selectValue.length
      }
    },
    async addCategory() {
      //级联  请求添加
      this.$refs.ruleForm.validate(async (res) => {
        console.log(res, this.ruleForm)
        if (res) {
          const { meta, data } = await this.$axios.post('/api/categories', {
            ...this.ruleForm,
          })
          console.log(meta, data)
          if (meta.status == 201) {
            this.getTableData()
            this.dialogVisible = false
            this.selectValue = ''
            this.ruleForm.cat_name = ''
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        }
      })
    },
    editData(val) {
      //编辑分类
      this.editDialogVisible = true
      this.editRuleForm.cat_name = val.cat_name
      this.editRuleForm.cat_id = val.cat_id
    },
    editCategory() {
      //编辑分类提交
      this.$refs.ruleForm1.validate(async (res) => {
        if (res) {
          const { meta } = await this.$axios.put(
            `/api/categories/${this.editRuleForm.cat_id}`,
            { cat_name: this.editRuleForm.cat_name }
          )
          if (meta.status == 200) {
            this.getTableData()
            this.$message.success('修改成功')
          } else {
            this.$message.success('修改失败')
          }

          this.editDialogVisible = false
        }
      })
    },
    async confirm(val) {
      const { meta } = await this.$axios.delete('/api/categories/' + val.cat_id)
      if (meta.status == 200) {
        this.getTableData()
        this.$message.success('删除成功')
      }
    },

    handleSizeChange(val) {
      // 改变显示页面数量
      this.query.pagesize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      //改变页码
      this.query.pagenum = val
      this.getTableData()
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch(() => {})
    },
  },
}
</script>

<style lang="less" scoped>
@import './categories.less';
</style>
